package ru.arriah.servicedesk.web.chief.action;

import java.io.IOException;
import java.text.DateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Locale;

import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ru.arriah.common.web.action.ActionMapping;
import ru.arriah.common.web.action.DumbAction;
import ru.arriah.servicedesk.bean.ClientBean;
import ru.arriah.servicedesk.bean.DepartmentBean;
import ru.arriah.servicedesk.bean.GroupBean;
import ru.arriah.servicedesk.bean.OrganizationBean;
import ru.arriah.servicedesk.bean.RequestBean;
import ru.arriah.servicedesk.bean.RequestPriorityBean;
import ru.arriah.servicedesk.bean.RequestTypeBean;
import ru.arriah.servicedesk.bean.error.RequestFormErrorBean;
import ru.arriah.servicedesk.ejb.ClientManagerLocalHome;
import ru.arriah.servicedesk.ejb.ClientManagerLocalObject;
import ru.arriah.servicedesk.ejb.EmployeeManagerLocalHome;
import ru.arriah.servicedesk.ejb.EmployeeManagerLocalObject;
import ru.arriah.servicedesk.ejb.GroupManagerLocalHome;
import ru.arriah.servicedesk.ejb.GroupManagerLocalObject;
import ru.arriah.servicedesk.ejb.OrganizationManagerLocalHome;
import ru.arriah.servicedesk.ejb.OrganizationManagerLocalObject;
import ru.arriah.servicedesk.ejb.RequestManagerLocalHome;
import ru.arriah.servicedesk.ejb.RequestManagerLocalObject;
import ru.arriah.servicedesk.help.Utils;
import ru.arriah.servicedesk.web.commonaction.exception.InternalException;

public class ProcessRequestAddFormAction extends DumbAction {
   protected RequestFormErrorBean requestFormErrorBean;
   
   protected OrganizationManagerLocalHome organizationManagerHome;
   protected RequestManagerLocalHome requestManagerHome;
   protected ClientManagerLocalHome clientManagerHome;
   protected GroupManagerLocalHome groupManagerHome;
   protected EmployeeManagerLocalHome employeeManagerHome;   
   
   public ProcessRequestAddFormAction() throws NamingException {
      super();

      requestManagerHome = 
         Utils.getRequestManagerHomeInterface();         
      
      organizationManagerHome =
        Utils.getOrganizationManagerHomeInterface();
      
      clientManagerHome =
        Utils.getClientManagerHomeInterface();
      
      groupManagerHome =
        Utils.getGroupManagerHomeInterface();
      
      employeeManagerHome =
        Utils.getEmployeeManagerHomeInterface();
   }
   
   private boolean isValid(RequestBean requestBean) {
     requestFormErrorBean = new RequestFormErrorBean();
     
     boolean result = true;     
     
     if(requestBean.isEmpty(requestBean.getName())) {
        requestFormErrorBean.setName(
           config.getProperty("ERROR.REQUESTFORM.NAME")
         );
         result = false; 
     }
     
     if(requestBean.getOrganizationId() == 0) {
       requestFormErrorBean.setOrganization(
         config.getProperty("ERROR.REQUESTFORM.ORGANIZATION")
       );
       result = false;
     }
     
     if(requestBean.getDepartmentId() == 0) {
       requestFormErrorBean.setDepartment(
         config.getProperty("ERROR.REQUESTFORM.DEPARTMENT")
       );
       result = false;
     }
     
     if(requestBean.getClientId() == 0) {
       requestFormErrorBean.setClient(
         config.getProperty("ERROR.REQUESTFORM.CLIENT")
       );
       result = false;
     }
     
     if (requestBean.getDispatcherText() == null || requestBean.getDispatcherText().equals("")) {
       requestFormErrorBean.setDispatcherText(
         config.getProperty("ERROR.REQUESTFORM.DISPATCHERTEXT")
       );
       result = false;
     }
     
     if(requestBean.getGroupId() == 0) {
       requestFormErrorBean.setGroup(
         config.getProperty("ERROR.REQUESTFORM.GROUP")
       );
       result = false;
     }
     
     if(requestBean.getRequestTypeId() == 0) {
       requestFormErrorBean.setRequestType(
         config.getProperty("ERROR.REQUESTFORM.REQUESTTYPE")
       );
       result = false;
     }  
     
     if (requestBean.getApproxEndDate() == null) {
       requestFormErrorBean.setApproxEndDate(
         config.getProperty("ERROR.REQUESTFORM.APPROX_END_DATE")
       );
       result = false;
     } else {       
       if (requestBean.getRegistrationDate().after(requestBean.getApproxEndDate()) 
          && !Utils.isSameDay(requestBean.getRegistrationDate(), requestBean.getApproxEndDate())
       ) {
         requestFormErrorBean.setApproxEndDate(
           String.format(
             config.getProperty("ERROR.REQUESTFORM.REGDATE_AFTER_END"),
             requestBean.getRegistrationDate()
           )
         );
         result = false;
       }
     }
     
     return result;
   }

   
   public String execute(
      ActionMapping actionMapping,
      HttpServletRequest request,
      HttpServletResponse response
   ) throws IOException, ServletException {
     try {
       RequestManagerLocalObject requestManager = 
         requestManagerHome.create();
       EmployeeManagerLocalObject employeeManager = 
         employeeManagerHome.create();
       
       RequestBean requestBean = new RequestBean();
       int userId = Utils.getUserId(request);       
              
       requestBean.setName(request.getParameter("name"));
       
       requestBean.setRegNumber(request.getParameter("regNumber"));
       
       requestBean.setOrganizationId(
         idVal(request.getParameter("organization_id"))
       );
       
       requestBean.setDepartmentId(
         idVal(request.getParameter("department_id"))
       ); 
       
       requestBean.setClientId(
         idVal(request.getParameter("client_id"))
       );
       
       requestBean.setRoom(request.getParameter("room"));
       
       requestBean.setDispatcherText(
         request.getParameter("dispatcherText")
       );
       
       requestBean.setGroupId(
         idVal(request.getParameter("group_id"))
       );       
       requestBean.setRequestTypeId(
        idVal(request.getParameter("requesttype_id"))
       );       
       requestBean.setComment(
         request.getParameter("comment")
       );
       requestBean.setPriority(idVal(request.getParameter("priority")));       
       requestBean.setRegistrationDate(new Date());
       
       DateFormat dateformat = 
          DateFormat.getDateInstance(
             DateFormat.SHORT, 
             new Locale("ru")
          );

       try {
         requestBean.setApproxEndDate(
           dateformat.parse(request.getParameter("approxEndDate"))
         );
       } catch (Exception e) {}
       
       requestBean.setStatusId(4); //active state
       
       requestBean.setRegistratorId(userId);
       
       int leadExecutorId = 
          employeeManager.selectLeadExecutorId(
             requestBean.getGroupId()
          );  
       
       requestBean.setLeadExecutorId(leadExecutorId); 
                                  
       if(!this.isValid(requestBean)) {     
         OrganizationManagerLocalObject organizationManager = 
           organizationManagerHome.create();         
         ClientManagerLocalObject clientManager = 
           clientManagerHome.create();         
         GroupManagerLocalObject groupManager = 
           groupManagerHome.create();
         
         //TODO replace to actual organization id
         Collection<DepartmentBean> departmentsList =
           organizationManager.selectDepartments(1);
         
         Collection<OrganizationBean> organizationsList = 
           organizationManager.selectOrganizations();
         
         Collection<ClientBean> clientsList = 
           clientManager.selectClientsByDepartment(
             requestBean.getDepartmentId()
           );
         
         Collection<RequestTypeBean> requestTypesList = 
           requestManager.selectRequestTypes();
         
         Collection<GroupBean> groupsList = 
           groupManager.selectGroups();
         
         Collection<RequestPriorityBean> priorityList = 
            requestManager.selectPriorityList();
                   
         organizationManager.remove();
         clientManager.remove();
         requestManager.remove();
         groupManager.remove();
         employeeManager.remove();
                           
         request.setAttribute("groupsList", groupsList);
         request.setAttribute("requestTypesList", requestTypesList);
         request.setAttribute("organizationsList", organizationsList);
         request.setAttribute("clientsList", clientsList);
         request.setAttribute("departmentsList", departmentsList);
         request.setAttribute("requestBean", requestBean);         
         request.setAttribute("error", requestFormErrorBean);
         request.setAttribute("priorityList", priorityList);
         
         addErrorMessage(
            request,
            config.getProperty("ERROR.REQUESTFORM_FIELDS_INVALID")
         );
                 
         return actionMapping.getFailureTarget();
       }
       
       if (requestManager.addRequest(requestBean, userId)) {               
         
          addInfMessage(
             request,
             String.format(config.getProperty("INF.REQUEST_ADDED"), requestBean.getId())
         );
          
       } else          
          addErrorMessage(
             request,
             config.getProperty("ERROR.REQUEST_NOT_ADDED")
          );                                    
       
       requestManager.remove();
       employeeManager.remove();
              
       return actionMapping.getSuccessTarget();
    } catch (Exception e) {
       handleException(e, "execute");
       throw new InternalException("ErrorMessage.internal");
    }
   }
}